#!/usr/bin/env python2
import sys
from os.path import basename, splitext

print "Reading " + sys.argv[1]+" ..."
with open(sys.argv[1], "r") as textFile:
    text = textFile.read().split()

print "Finding Categories ..."
categories = []
for cat in text:
    pair = cat.split(":")
    if (pair[0] not in categories):
        categories.append(pair[0])

print "Finding values ..."
output = []
for i in xrange(len(categories)):
    output.append([])
for cat in text:
    pair = cat.split(":")
    output[categories.index(pair[0])].append(pair[1])

print "Formatting & writing to "+splitext(basename(sys.argv[1]))[0] + ".csv ..."
with open(splitext(basename(sys.argv[1]))[0] + ".csv", "w") as csvFile:
    catString = ""
    for i in categories:
        catString = catString + i + ","
    csvFile.write(catString[:-1] + "\n")
    
    outt = zip(*output[::-1])
    for i in xrange(len(outt)):
        valString = ""
        for j in xrange(len(outt[i][::-1])):
            valString = valString + outt[i][::-1][j] + ","
        csvFile.write(valString[:-1] + "\n")
print "Done!"
